package mvc.controller;

import mvc.model.pojos.CartBean;
import mvc.model.pojos.UserBean;
import mvc.model.service.CartService;
import mvc.model.service.impl.CartServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AddCartServlet", urlPatterns = "/addcart")
public class AddCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CartBean cartBean = getCartBean(request);

        cartBean.setChecked(0);

        CartService cartService = new CartServiceImpl();
        CartBean cartBean1 = cartService.queryByPid(cartBean.getPid(), cartBean.getUid());

        if (cartBean1 != null) {
            cartBean.setCount(cartBean1.getCount() + cartBean.getCount());
        }
        cartService.addCart(cartBean);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        CartBean cartBean = getCartBean(request);

        cartBean.setChecked(1);

        CartService cartService = new CartServiceImpl();
        CartBean cartBean1 = cartService.queryByPid(cartBean.getPid(), cartBean.getUid());
        if (cartBean1 != null) {
            cartBean1.setFlag(0);
            cartService.upCart(cartBean1, cartBean1.getCartnumber());
        }
        cartService.upCartAll(cartBean.getUid(), 0);

        cartService.addCart(cartBean);
        response.getWriter().append("ok");

    }

    private CartBean getCartBean(HttpServletRequest request) {
        String pid = request.getParameter("pid");
        String count = request.getParameter("count");
        UserBean user = (UserBean) request.getSession().getAttribute("user");


        CartBean cartBean = new CartBean();
        cartBean.setPid(Integer.parseInt(pid));
        cartBean.setCount(Integer.parseInt(count));
        cartBean.setUid(user.getUid());

        return cartBean;
    }
}
